﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Productsearch_result : System.Web.UI.Page
{
    private List<Product> matchedProducts;
    private List<Product> filteredProducts;
    private IEnumerable<Product> sortedProducts;

    string keywords;

    protected void Page_Load(object sender, EventArgs e)
    {
        keywords = Request.QueryString["q"];
        keywordsLabel.Text = keywords;
        searchBox.Keyword = keywords;


        GetSearchResult();
        GetFilteredResult();
        GetSortedResult();
    }


    private void GetSearchResult()
    {
        var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
        if (connString == null)
            throw new ArgumentNullException("无法获取指定的数据库连接字符串。");

        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {
            connection.Open();

            SqlCommand command = new SqlCommand(
                string.Format(@"
SELECT   *
FROM      RatedProduct
WHERE name like '%{0}%'
", keywords),
                connection);
            command.CommandType = System.Data.CommandType.Text;
            var reader = command.ExecuteReader();

            matchedProducts = new List<Product>();
            while (reader.Read())
            {
                matchedProducts.Add(new Product
                {
                    Id = reader.GetInt32(0),
                    Name = reader.GetString(1),
                    Price = reader.GetDecimal(2),
                    Discount = reader.GetByte(3),
                    CoverPhoto = reader.IsDBNull(7) ? string.Empty : reader.GetString(7),

                    Owner = reader.GetString(9),
                    Rating = reader.IsDBNull(10) ? 0 : reader.GetDecimal(10),
                    SoldAmount = reader.GetInt32(11),
                    Category = reader.GetString(12)
                });
            }
        }
    }

    void GetFilteredResult()
    {
        Contract.Requires(matchedProducts != null);

        //用categorylist 对matchedProducts进行筛选
        if (productCategoryList.SelectedIndex == -1)
        {
            filteredProducts = matchedProducts;
        }
        else
        {

            filteredProducts = new List<Product>();
            for (int i = 0; i < productCategoryList.Items.Count; i++)
            {
                if (productCategoryList.Items[i].Selected)
                {
                    var r = from product in matchedProducts
                            where product.Category == productCategoryList.Items[i].Text
                            select product;
                    filteredProducts.AddRange(r);
                }
            }
        }



        //应用Greater than过滤条件
        if (greaterThanCheckBox.Checked)
        {
            int i = 0;
            while (i < filteredProducts.Count)
            {
                if (!(filteredProducts[i].Price > Convert.ToDecimal(highPriceTextBox.Text)))
                    filteredProducts.RemoveAt(i);
                else
                    i++;
            }
        }

        //应用Less than过滤条件
        if (lessThanCheckBox.Checked)
        {
            var p = from product in filteredProducts
                    where product.Price < Convert.ToDecimal(lowPriceTextBox.Text)
                    select product;
            filteredProducts = new List<Product>(p);

            int i = 0;
            while (i < filteredProducts.Count)
            {
                if (!(filteredProducts[i].Price < Convert.ToDecimal(lowPriceTextBox.Text)))
                    filteredProducts.RemoveAt(i);
                else
                    i++;
            }
        }
    }


    private void GetSortedResult()
    {
        switch (sortingMethodList.SelectedValue)
        {
            case "Natural Order":
                sortedProducts = filteredProducts;
                break;
            case "Sold Amount":
                sortedProducts = from p in filteredProducts
                                 orderby p.SoldAmount ascending
                                 select p;
                break;
            case "Rating":
                sortedProducts = from p in filteredProducts
                                 orderby p.Rating ascending
                                 select p;
                break;
            case "Price":
                sortedProducts = from p in filteredProducts
                                 orderby p.Price ascending
                                 select p;
                break;
            case "Discount":
                sortedProducts = from p in filteredProducts
                                 orderby p.Discount descending
                                 select p;
                break;
            default:
                throw new ArgumentOutOfRangeException("sortingMethodList的选中项的值超出意料范围。");
        }
    }

    protected void searchResultSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        e.Result = matchedProducts;
    }


    protected void sortedResultSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        e.Result = sortedProducts;
    }


    protected void categorySource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        e.Result = (from p in matchedProducts
                    select p.Category).Distinct();
    }



    protected void priceFilterButton_Click(object sender, EventArgs e)
    {

    }

    public class Product
    {
        public int Id { get; set; }
        //需要
        public string Name { get; set; }
        //需要
        public decimal Price { get; set; }
        //需要
        public int Discount { get; set; }
        //需要
        public string Description { get; set; }

        public string Shop { get; set; }

        public short InventoryLevel { get; set; }
        //需要
        public string CoverPhoto { get; set; }

        public string Category { get; set; }

        public decimal Rating { get; set; }

        public int SoldAmount { get; set; }

        public string Owner { get; set; }


    }
}